import React, {useEffect, useRef} from "react";
import {DatePicker} from 'antd';
import dayjs, {Dayjs} from "dayjs";

export interface dateEditorProps {
    defaultValue?: string;
    onCommit?: (val: any) => void;
}

const dateFormat = 'YYYY/MM/DD';
const getToday = () => {
    var today = dayjs().format('YYYY-MM-DD');
    console.log(today)
    return today;
}
const dateEditor: React.FC<dateEditorProps> = ({defaultValue = getToday(), onCommit}) => {
    const [value, setValue] = React.useState(defaultValue);
    const [isOpen, setIsOpen] = React.useState(false);
    const editorRef = useRef<any>(null);
    useEffect(() => {
        if (editorRef.current) {
            editorRef.current.focus();
            setIsOpen(true)
        }
    }, [editorRef]);
    const keyDownHanle = (e: React.KeyboardEvent) => {
        if (e.code == 'Enter') {
            onCommit && onCommit(value)
            e.stopPropagation(); // 阻止事件冒泡
        }
    }
    const onDateChangeHandle = (date: Dayjs, dateString: string | string[]) => {
        console.log(date)
        onCommit&&onCommit(date.toString())
    }
    return (
        <DatePicker open={isOpen} ref={editorRef} onKeyDown={keyDownHanle} style={{width: '100%'}}
                    defaultValue={dayjs(value, dateFormat)}
                    onBlur={e=> {
                        // @ts-ignore
                        onCommit&&onCommit(e.target.value)
                        setIsOpen(false)
                    }}
                    format={dateFormat} onChange={onDateChangeHandle}/>
    )
}

export default dateEditor